package grpc

import (
	"context"
	"net"

	"vdrift/internal/logger"
	pb "vdrift/pkg/proto"

	"github.com/sirupsen/logrus"
	"google.golang.org/grpc"
)

type Server struct {
	pb.UnimplementedVdriftServer
	stateCh chan<- pb.NodeState
}

func (s *Server) ReportState(ctx context.Context, in *pb.NodeState) (*pb.Empty, error) {
	select {
	case s.stateCh <- *in:
	default:
	}
	return &pb.Empty{}, nil
}

func StartServer(port string, stateCh chan<- pb.NodeState) {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		logger.WithError(err).Fatal("failed to listen gRPC")
	}

	s := grpc.NewServer()
	pb.RegisterVdriftServer(s, &Server{stateCh: stateCh})

	logrus.WithField("port", port).Info("gRPC server started")
	if err := s.Serve(lis); err != nil {
		logger.WithError(err).Fatal("gRPC server failed")
	}
}
